<template>
  <div class="avatar">
    <Header class="head-nft-creator" />
    <div class="avatar__theme">
      <div class="wrapper">
        <div class="content">
          <div class="theme" v-for="(item, i) in themeList" :key="i">
            <div class="theme__name">
              <span>{{ item.name }}</span>
            </div>
            <div class="theme__pic" @click="changeTheme(item)">
              <img :src="item.icon" />
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="fold">
        <img src="@/assets/creator/icon/icon-right.svg" />
      </div> -->
    </div>
    <div class="avatar__main">
      <Preview
        :value="svg"
        :bgColor="bgColor"
        :bgShape="bgShape"
        :name="name"
        :author="author"
        :license="license"
        :prev-enable="prevEnable"
        :next-enable="nextEnable"
        :options="options"
        @random="random"
        @next="next"
        @prev="prev"
        @load="loadNFT"
      />
      <Works :list="nftList" />
    </div>
    <div class="avatar__side">
      <div class="wrapper">
        <div class="content">
          <Setting title="Avatar Shape">
            <div class="shape">
              <Shape
                v-for="(item, i) in bgShapeList"
                :key="i"
                :value="item"
                :active="item === bgShape"
                @change="drawBg('bgShape', item)"
              />
            </div>
          </Setting>
          <Setting title="Background Color" v-if="config.bgColor">
            <div class="bgcolor">
              <Color
                v-for="(item, i) in bgColorList"
                :key="i"
                :value="item"
                :active="item === bgColor"
                @change="drawBg('bgColor', item)"
              />
            </div>
          </Setting>
          <div v-for="(list, i) in components" :key="i">
            <Setting :title="i" v-if="Object.keys(list).length > 1">
              <div class="widget-list">
                <Widget
                  v-for="(item, j) in list"
                  :key="j"
                  :value="getValue(item)"
                  :active="checkActive(j, i)"
                  @click.native="draw(i, j)"
                />
                <Widget
                  value="empty"
                  :active="!options[i]"
                  @click.native="drawEmpty(i)"
                />
              </div>
            </Setting>
            <Setting v-if="colors[i]" :title="i + '\'s Color'">
              <div class="bgcolor">
                <Color
                  v-for="(item, j) in colors[i]"
                  :key="j"
                  :name="j"
                  :value="item"
                  :active="checkActive(j, i + 'Color')"
                  @change="draw(i + 'Color', j)"
                />
                <Color
                  value="empty"
                  :active="!options[i + 'Color']"
                  @click.native="drawEmpty(i + 'Color')"
                />
              </div>
            </Setting>
          </div>
          <div v-for="(list, i) in otherColors" :key="i">
            <Setting :title="i + 'Color'">
              <div class="bgcolor">
                <Color
                  v-for="(item, j) in list"
                  :key="j"
                  :name="j"
                  :value="item"
                  :active="checkActive(j, i + 'Color')"
                  @change="draw(i + 'Color', j)"
                />
                <Color
                  value="empty"
                  :active="!options[i + 'Color']"
                  @click.native="drawEmpty(i + 'Color')"
                />
              </div>
            </Setting>
          </div>
        </div>
      </div>
      <!-- <div class="fold">
        <img src="@/assets/creator/icon/icon-right.svg" />
      </div> -->
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header";
import Setting from "./components/Setting";
import Shape from "./components/Shape";
import Color from "./components/Color";
import Works from "./components/Works";
import Preview from "./components/Preview";
import Widget from "./components/Widget";

import { createAvatar } from "@dicebear/avatars";
import { themeList } from "./theme";

import { mapState } from "vuex";
import { getNFTList } from "@/api/core";

export default {
  components: {
    Header,
    Setting,
    Shape,
    Works,
    Color,
    Preview,
    Widget,
  },
  data() {
    const theme = window.localStorage.getItem("theme") || "micah";
    const {
      name,
      author,
      license,
      style,
      alias = {},
      config = {},
      options = {},
      viewBox,
    } = themeList.filter((item) => {
      return item.code === theme;
    })[0];
    const baseColors = this.getBaseColors(style);
    return {
      theme,
      style,
      name,
      alias,
      config,
      author,
      license,
      viewBox,
      themeList,
      baseColors,
      options,
      bgShape: "squircle",
      bgShapeList: ["circle", "square", "squircle"],
      bgColor: "#6BD9E9",
      bgColorList: [
        "#6BD9E9",
        "#FC909F",
        "#F4D150",
        "#E0DDFF",
        "#D2EFF3",
        "#FFEDEF",
        "#FFEBA4",
        "#506AF4",
        "#F48150",
        "#48A99A",
        "#C09FFF",
        "#FD6F5D",
        "linear-gradient(45deg, #E3648C, #D97567)",
        "linear-gradient(62deg, #8EC5FC, #E0C3FC)",
        "linear-gradient(90deg, #ffecd2, #fcb69f)",
        "linear-gradient(120deg, #a1c4fd, #c2e9fb)",
        "linear-gradient(-135deg, #fccb90, #d57eeb)",
      ],
      actionSeq: 0,
      actionList: [],
      svg: "",
      colors: style.colors,
      components: style.components,
      nftList: [],
    };
  },
  computed: {
    ...mapState({
      account: (state) => state.account,
    }),
    prevEnable() {
      return (
        this.actionList && this.actionList.length > 0 && this.actionSeq > 0
      );
    },
    nextEnable() {
      return (
        this.actionList &&
        this.actionList.length > 0 &&
        this.actionSeq < this.actionList.length - 1
      );
    },
    otherColors() {
      const { components, colors } = this.style;
      const otherColors = {};
      for (var key in colors) {
        if (!components[key]) {
          otherColors[key] = colors[key];
        }
      }
      return otherColors;
    },
  },
  watch: {
    account() {
      this.loadNFT();
    },
  },
  mounted() {
    this.load();
    this.loadNFT();
  },
  methods: {
    async loadNFT() {
      if (!this.account) return;

      const list = await getNFTList(this.account);
      this.nftList = list;
    },
    checkActive(val1, val2) {
      const key = this.options[val2];
      return key && key[0] && val1 === key[0];
    },
    getValue(val) {
      try {
        if (typeof val === "function") {
          const result = val({}, this.baseColors);
          return `<svg viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg"><g>${result}</g></svg>`;
        }
        return val;
      } catch (e) {
        console.log(val, e);
        return "e";
      }
    },
    getBaseColors(style) {
      const { colors } = style;
      const baseColors = {};
      for (var key in colors) {
        baseColors[key] = {
          value: "#fff",
        };
      }
      return baseColors;
    },
    load() {
      console.log("options", this.options);
      const svg = createAvatar(this.style, {
        seed: "custom-seed",
        size: "280",
        accessoiresProbability: 100,
        ...this.options,
      });
      this.svg = svg;
    },
    random() {
      for (var key in this.components) {
        const obj = this.components[key];
        const keys = Object.keys(obj);
        if (keys && keys.length && keys.length > 1) {
          const val = keys[Math.floor(keys.length * Math.random())];
          this.options[key] = [val];
        }
      }
      this.bgColor = this.getRandomColor(this.bgColorList);
      this.load();
    },
    getRandomColor(list) {
      const index = Math.ceil(list.length * Math.random());
      return list[index];
    },
    draw(key, value) {
      const key2 = this.alias[key];
      console.log("key, key2, val", key, key2, value);
      this.options[key] = [value];
      if (key2) {
        this.options[key2] = [value];
      }
      this.actionList.push({
        type: "01",
        key,
        value,
      });
      this.actionSeq = this.actionList.length - 1;
      this.load();
    },
    drawBg(key, value) {
      this.actionList.push({
        type: "02",
        key,
        value,
      });
      this.actionSeq = this.actionList.length - 1;
      this[key] = value;
    },
    drawEmpty(key) {
      delete this.options[key];
      if (this.alias[key]) {
        delete this.options[this.alias[key]];
      }
      this.load();
    },
    reDraw(action) {
      const { type, key, value } = action;
      switch (type) {
        case "01":
          this.options[key] = [value];
          this.load();
          break;
        case "02":
          this[key] = value;
          break;
      }
    },
    prev() {
      if (!this.prevEnable) return;
      this.actionSeq = this.actionSeq - 1;
      this.reDraw(this.actionList[this.actionSeq]);
    },
    next() {
      console.log("this.actionSeq", this.actionSeq, this.actionList);
      if (!this.nextEnable) return;
      this.actionSeq = this.actionSeq + 1;
      this.reDraw(this.actionList[this.actionSeq]);
    },
    changeTheme(data) {
      const {
        code,
        name,
        author,
        license,
        style,
        alias = {},
        config = {},
        options = {},
        viewBox,
      } = data;
      const { components, colors } = style;
      const baseColors = this.getBaseColors(style);
      this.theme = code;
      this.name = name;
      this.author = author;
      this.viewBox = viewBox;
      this.license = license;
      this.style = style;
      this.colors = colors;
      this.alias = alias;
      this.config = config;
      this.components = components;
      this.baseColors = baseColors;
      this.options = options;
      window.localStorage.setItem("theme", code);
      this.load();
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar {
  position: relative;
  width: 100vw;
  display: flex;
  background-color: #14161a;

  &__theme {
    position: relative;

    .wrapper {
      .content {
        display: grid;
        grid-template-columns: 1fr 1fr;
      }
    }

    .theme {
      margin-bottom: 25px;
      padding-bottom: 30px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
      &__pic {
        height: 120px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        img {
          cursor: pointer;
          height: 100px;
          transition: all 0.3s ease;
          &:hover {
            transform: scale(1.15);
          }
        }
      }

      &__name {
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-bottom: 25px;
        span {
          font-size: 16px;
          font-family: "Roboto Medium";
          color: var(--color);
          text-transform: capitalize;
        }
      }
    }

    .fold {
      right: -20px;
      border-radius: 0 6px 6px 0;

      img {
        transform: rotate(180deg) scale(0.8);
        transition: transform 0.2s;
      }

      &:hover {
        img {
          transform: rotate(180deg) scale(0.8) translateX(2px);
        }
        background-color: rgba(255, 255, 255, 0.08);
      }
    }
  }
  &__main {
    height: 100vh;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    overflow: hidden;
  }
  &__side {
    position: relative;

    .fold {
      left: -20px;
      border-radius: 6px 0 0 6px;
      img {
        transform: scale(0.8);
        transition: transform 0.2s;
      }

      &:hover {
        img {
          transform: scale(0.8) translateX(2px);
        }
        background-color: rgba(255, 255, 255, 0.08);
      }
    }

    .wrapper {
      .content {
        width: 410px !important;
      }
    }
  }

  .wrapper {
    padding-top: 72px;
    height: 100vh;
    box-sizing: border-box;
    background-color: rgba(255, 255, 255, 0.05);
    .content {
      height: 100%;
      width: 340px;
      padding: 20px 30px 30px;
      overflow: auto;
      box-sizing: border-box;
    }
  }
}

.shape {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.bgcolor {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
}

.widget-list {
  display: grid;
  grid-gap: 3px;
  grid-template-columns: 1fr 1fr 1fr 1fr;
}
</style>
